<template>
  <div class="login">
    <div class="logo">
      <h1>光谷智慧交通系统</h1>
    </div>
    <div class="loginBox">
      <h2>登 录</h2>
      <el-tabs v-model="userType" class="demo-tabs">
        <el-tab-pane label="普通用户" name="common"></el-tab-pane>
        <el-tab-pane label="交通部门" name="traffic"></el-tab-pane>
        <el-tab-pane label="管理员" name="admin"></el-tab-pane>
      </el-tabs>
      <el-form :model="loginForm" :rules="rules" @submit.prevent="handleLogin">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="用户名" clearable />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <PuzzleCaptcha
        ref="captchaRef"
        :show="isLook"
        @success="handleCaptchaSuccess"
        @close="isLook = false"
      />
      <div class="remember">
        <el-checkbox v-model="loginForm.remember">
          <span>记住我</span>
        </el-checkbox>
        <p>
          <router-link to="/changepassword">修改密码</router-link>
        </p>
      </div>
      <div class="loginBtn">
        <el-button type="primary" plain @click="showCaptcha"> 立即登录 </el-button>
      </div>
      <p class="error">
        没有账号？
        <router-link v-if="userType === 'common'" to="/register">立即注册</router-link>
        <span v-else>立即注册</span>
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElForm, ElFormItem } from 'element-plus'
import axios from 'axios'
import PuzzleCaptcha from '@/components/PuzzleCaptcha.vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const userType = ref('common')
const captchaRef = ref(null)
const loginForm = ref({
  username: '',
  password: '',
  remember: false,
})
const isLook = ref(false) //是否显示验证码

// 监听 remember 变化
watch(
  () => loginForm.value.remember,
  (newVal) => {
    if (!newVal) {
      localStorage.removeItem('user') // 取消勾选时立即清除
    }
  },
)

// 页面加载时，如果记住密码，自动填充用户名和密码
onMounted(() => {
  const savedUser = localStorage.getItem('user')
  if (savedUser) {
    const user = JSON.parse(savedUser)
    loginForm.value.username = user.username
    loginForm.value.password = user.password
    loginForm.value.remember = true
  } else {
    loginForm.value.remember = false
  }
})

// 新增显示验证码的方法
const showCaptcha = () => {
  // 先进行简单的表单验证
  if (!loginForm.value.username || !loginForm.value.password) {
    ElMessage.warning('请输入用户名和密码')
    return
  }
  isLook.value = true
}

// 新增验证码验证成功回调
const handleCaptchaSuccess = () => {
  isLook.value = false
  // 这里执行实际的登录逻辑
  handleLogin()
}

// 登录逻辑
const handleLogin = () => {
  axios
    .post('http://localhost:3001/login', {
      username: loginForm.value.username,
      password: loginForm.value.password,
    })
    .then((res) => {
      if (res.status === 200) {
        const type = res.data.data.data.type
        if (type !== userType.value) {
          ElMessage.error('身份选择错误')
          return
        }
        ElMessage.success('登录成功')
        // 存储 JWT 到本地存储
        localStorage.setItem('token', res.data.token)
        // 存储 userId 到本地存储
        localStorage.setItem('userId', res.data.data.data.id)
        if (loginForm.value.remember) {
          // 记住密码，存储用户名和密码到本地存储
          localStorage.setItem(
            'user',
            JSON.stringify({
              username: loginForm.value.username,
              password: loginForm.value.password,
            }),
          )
        } else {
          // 不记住密码，清除本地存储的用户名和密码
          localStorage.removeItem('user')
        }

        // 更新用户的 isOnline 状态为 true
        const userId = res.data.data.data.id
        const token = res.data.token
        axios
          .put(
            'http://localhost:3001/updateuser',
            {
              id: userId,
              userObj: { isOnline: true },
            },
            { headers: { Authorization: `Bearer ${token}` } },
          )
          .then(() => {
            router.push({
              path: `/main/${type}`,
              //避免用户名是特殊字符带来的影响
              query: { username: loginForm.value.username },
            })
          })
          .catch((error) => {
            console.error('更新用户在线状态出错:', error)
            ElMessage.error('更新用户在线状态出错，请稍后重试')
          })
      } else {
        ElMessage.error('登录失败')
      }
    })
    .catch((error) => {
      if (error.response.status === 401) {
        ElMessage.error('用户名或密码错误')
      } else {
        ElMessage.error('服务器异常，请稍后重试')
      }
    })
}

// 增加密码验证规则
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' },
  ],
}
</script>

<style lang="scss" scoped>
.login {
  a {
    color: #409eff;
    text-decoration: none;
  }
  position: relative;
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 100vh;
  background-image: url('/images/bg.png');
  background-size: cover;

  h1 {
    position: absolute;
    top: 40%;
    left: 25%;
    transform: translate(-50%, -50%);
    color: #fff;
    font-size: 80px;
    font-weight: bold;
    text-shadow: 2px 2px 5px #999;
  }

  .loginBox {
    position: absolute;
    top: 50%;
    left: 70%;
    transform: translate(-50%, -50%);
    width: 450px;
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
    border-radius: 10px;
    background-color: #fff;
    border-bottom: 20px;

    h2 {
      text-align: center;
      font-size: 30px;
      color: #333;
      margin-bottom: 20px;
    }

    :deep(.el-tabs__item) {
      width: 100px;
      font-size: 18px;
      color: #575757;
      &.is-active {
        color: #409eff;
      }
    }

    .el-form {
      margin-top: 10px;
      .el-input {
        width: 300px;
        margin-bottom: 10px;
      }
    }

    .remember {
      display: flex;
      justify-content: space-around;
      align-items: center;
      gap: 165px;
      width: 300px;
      margin-bottom: 20px;
    }

    .loginBtn {
      .el-button {
        padding: 5px;
        margin-bottom: 20px;
      }
    }

    p {
      text-align: center;
      font-size: 14px;
      color: #6b6b6b;
    }
    .error {
      span {
        color: #999;
        cursor: not-allowed;
      }
    }
  }
}
</style>
